const baseUrl = 'https://movie.douban.com/subject/';
const doubanId = '26985127';
// http://vt1.doubanio.com/201808141049/69ce635356e6fdfaa6027aa44a3c1099/view/movie/M/402340740.mp4

const puppeteer = require('puppeteer');
// const path = require('path');

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

(async () => {
  try {
    console.log('Start')
    const browser = await puppeteer.launch({
      // headless: false
    });
    const page = await browser.newPage();
    await page.goto(baseUrl + doubanId, {
      timeout: 300000,
      waitUntil: 'networkidle2'
    });
    await sleep(1000);
    const result = await page.evaluate(() => {
      const $ = window.$;
      const videoPic = $('.related-pic-video'); 
      if (videoPic && videoPic.length > 0) {
          const link = videoPic.attr('href');
          const cover = videoPic.css("backgroundImage").replace('url("','').replace('")','');
          return {
              link,
              cover
          }
      }
      return {};
    })

    // console.log(result);

    let video;
    // 爬取预告片video 
    if (result.link) {
        await page.goto(result.link, {
            timeout: 30000,
            waitUntil: 'networkidle2'
        })
        await sleep(2000);
        video = await page.evaluate(() => {
            const $ = window.$;
            const videoSource = $('source');
            if (videoSource && videoSource.length > 0) {
                return videoSource.attr('src');
            }
            return '';
        })
    }

    // 包装最后数据
    const data = {
        doubanId,
        cover: result.cover,
        video,
    }

    await browser.close();

    process.send(data);
    process.exit(0);

  } catch (error) {
    console.log(`错误${error}`);
  }
})();